<!DOCTYPE html>
<html lang="zh-Hans">
    <!-- title -->




<!-- keywords -->




<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="author" content="Yeungeek">
    <meta name="renderer" content="webkit">
    <meta name="copyright" content="Yeungeek">
    
    <meta name="keywords" content="hexo,hexo-theme,hexo-blog,Android,yeungeek">
    
    <meta name="description" content="It's my Androad">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Android NDK-深入理解JNI · Android 沉思录</title>
    <style type="text/css">
    @font-face {
        font-family: 'Oswald-Regular';
        src: url("/font/Oswald-Regular.ttf");
    }

    body {
        margin: 0;
    }

    header,
    footer,
    .back-top,
    .sidebar,
    .container,
    .site-intro-meta,
    .toc-wrapper {
        display: none;
    }

    .site-intro {
        position: relative;
        z-index: 3;
        width: 100%;
        /* height: 50vh; */
        overflow: hidden;
    }

    .site-intro-placeholder {
        position: absolute;
        z-index: -2;
        top: 0;
        left: 0;
        width: calc(100% + 300px);
        height: 100%;
        background: repeating-linear-gradient(-45deg, #444 0, #444 80px, #333 80px, #333 160px);
        background-position: center center;
        transform: translate3d(-226px, 0, 0);
        animation: gradient-move 2.5s ease-out 0s infinite;
    }

    @keyframes gradient-move {
        0% {
            transform: translate3d(-226px, 0, 0);
        }
        100% {
            transform: translate3d(0, 0, 0);
        }
    }

</style>

    <link rel="preload" href="/css/style.css?v=20180824" as="style" onload="this.onload=null;this.rel='stylesheet'">
    <link rel="stylesheet" href="/css/mobile.css?v=20180824" media="(max-width: 980px)">
    
    <link rel="preload" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
    
    <!-- /*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
/* This file is meant as a standalone workflow for
- testing support for link[rel=preload]
- enabling async CSS loading in browsers that do not support rel=preload
- applying rel preload css once loaded, whether supported or not.
*/ -->
<script>
(function( w ){
	"use strict";
	// rel=preload support test
	if( !w.loadCSS ){
		w.loadCSS = function(){};
	}
	// define on the loadCSS obj
	var rp = loadCSS.relpreload = {};
	// rel=preload feature support test
	// runs once and returns a function for compat purposes
	rp.support = (function(){
		var ret;
		try {
			ret = w.document.createElement( "link" ).relList.supports( "preload" );
		} catch (e) {
			ret = false;
		}
		return function(){
			return ret;
		};
	})();

	// if preload isn't supported, get an asynchronous load by using a non-matching media attribute
	// then change that media back to its intended value on load
	rp.bindMediaToggle = function( link ){
		// remember existing media attr for ultimate state, or default to 'all'
		var finalMedia = link.media || "all";

		function enableStylesheet(){
			link.media = finalMedia;
		}

		// bind load handlers to enable media
		if( link.addEventListener ){
			link.addEventListener( "load", enableStylesheet );
		} else if( link.attachEvent ){
			link.attachEvent( "onload", enableStylesheet );
		}

		// Set rel and non-applicable media type to start an async request
		// note: timeout allows this to happen async to let rendering continue in IE
		setTimeout(function(){
			link.rel = "stylesheet";
			link.media = "only x";
		});
		// also enable media after 3 seconds,
		// which will catch very old browsers (android 2.x, old firefox) that don't support onload on link
		setTimeout( enableStylesheet, 3000 );
	};

	// loop through link elements in DOM
	rp.poly = function(){
		// double check this to prevent external calls from running
		if( rp.support() ){
			return;
		}
		var links = w.document.getElementsByTagName( "link" );
		for( var i = 0; i < links.length; i++ ){
			var link = links[ i ];
			// qualify links to those with rel=preload and as=style attrs
			if( link.rel === "preload" && link.getAttribute( "as" ) === "style" && !link.getAttribute( "data-loadcss" ) ){
				// prevent rerunning on link
				link.setAttribute( "data-loadcss", true );
				// bind listeners to toggle media back
				rp.bindMediaToggle( link );
			}
		}
	};

	// if unsupported, run the polyfill
	if( !rp.support() ){
		// run once at least
		rp.poly();

		// rerun poly on an interval until onload
		var run = w.setInterval( rp.poly, 500 );
		if( w.addEventListener ){
			w.addEventListener( "load", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		} else if( w.attachEvent ){
			w.attachEvent( "onload", function(){
				rp.poly();
				w.clearInterval( run );
			} );
		}
	}


	// commonjs
	if( typeof exports !== "undefined" ){
		exports.loadCSS = loadCSS;
	}
	else {
		w.loadCSS = loadCSS;
	}
}( typeof global !== "undefined" ? global : this ) );
</script>

    <link rel="icon" href="/assets/favicon.ico">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js" as="script">
    <link rel="preload" href="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js" as="script">
    <link rel="preload" href="/scripts/main.js" as="script">
    <link rel="preload" as="font" href="/font/Oswald-Regular.ttf" crossorigin>
    <link rel="preload" as="font" href="https://at.alicdn.com/t/font_327081_1dta1rlogw17zaor.woff" crossorigin>
    
    <!-- fancybox -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" defer></script>
    <!-- 百度统计  -->
    
    <script>
        var _hmt = _hmt || [];
        (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?75ae37defe17129870bc1ba88b527367";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
        })();
    </script>
    
    <!-- 谷歌统计  -->
    
    <script>
        (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
        (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
        })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
        ga('create', 'UA-37469819-1', 'auto');
        ga('send', 'pageview');
    </script>
    
</head>

    
        <body class="post-body">
    
    
<header class="header">

    <div class="read-progress"></div>
    <div class="header-sidebar-menu">&#xe775;</div>
    <!-- post页的toggle banner  -->
    
    <div class="banner">
            <div class="blog-title">
                <a href="/">Android 沉思录</a>
            </div>
            <div class="post-title">
                <a href="#" class="post-name">Android NDK-深入理解JNI</a>
            </div>
    </div>
    
    <a class="home-link" href="/">Android 沉思录</a>
</header>
    <div class="wrapper">
        <div class="site-intro" style="







height:40vh;
">
    
    <!-- 主页  -->
    
    
    <!-- 404页  -->
            
    <div class="site-intro-placeholder"></div>
    <div class="site-intro-img" style="background-image: url(/intro/post-bg.jpg)"></div>
    <div class="site-intro-meta">
        <!-- 标题  -->
        <h1 class="intro-title">
            <!-- 主页  -->
            
            Android NDK-深入理解JNI
            <!-- 404 -->
            
        </h1>
        <!-- 副标题 -->
        <p class="intro-subtitle">
            <!-- 主页副标题  -->
            
            
            <!-- 404 -->
            
        </p>
        <!-- 文章页meta -->
        
            <div class="post-intros">
                <!-- 文章页标签  -->
                
                    <div class="post-intro-tags">
    
        <a class="post-tag" href="javascript:void(0);" data-tags="JNI">JNI</a>
    
        <a class="post-tag" href="javascript:void(0);" data-tags="NDK">NDK</a>
    
</div>
                
                
                    <div class="post-intro-read">
                        <span>字数统计: <span class="post-count word-count">3.4k</span>阅读时长: <span class="post-count reading-time">15 min</span></span>
                    </div>
                
                <div class="post-intro-meta">
                    <span class="post-intro-calander iconfont-archer">&#xe676;</span>
                    <span class="post-intro-time">2019/08/21</span>
                    
                    <span id="busuanzi_container_page_pv" class="busuanzi-pv">
                        <span class="iconfont-archer">&#xe602;</span>
                        <span id="busuanzi_value_page_pv"></span>
                    </span>
                    
                    <span class="shareWrapper">
                        <span class="iconfont-archer shareIcon">&#xe71d;</span>
                        <span class="shareText">Share</span>
                        <ul class="shareList">
                            <li class="iconfont-archer share-qr" data-type="qr">&#xe75b;
                                <div class="share-qrcode"></div>
                            </li>
                            <li class="iconfont-archer" data-type="weibo">&#xe619;</li>
                            <li class="iconfont-archer" data-type="qzone">&#xe62e;</li>
                            <li class="iconfont-archer" data-type="twitter">&#xe634;</li>
                            <li class="iconfont-archer" data-type="facebook">&#xe67a;</li>
                        </ul>
                    </span>
                </div>
            </div>
        
    </div>
</div>
        <script>
 
  // get user agent
  var browser = {
    versions: function () {
      var u = window.navigator.userAgent;
      return {
        userAgent: u,
        trident: u.indexOf('Trident') > -1, //IE内核
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
        iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
        iPad: u.indexOf('iPad') > -1, //是否为iPad
        webApp: u.indexOf('Safari') == -1, //是否为web应用程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') == -1, //是否为微信浏览器
        uc: u.indexOf('UCBrowser') > -1 //是否为android下的UC浏览器
      };
    }()
  }
  console.log("userAgent:" + browser.versions.userAgent);

  // callback
  function fontLoaded() {
    console.log('font loaded');
    if (document.getElementsByClassName('site-intro-meta')) {
      document.getElementsByClassName('intro-title')[0].classList.add('intro-fade-in');
      document.getElementsByClassName('intro-subtitle')[0].classList.add('intro-fade-in');
      var postIntros = document.getElementsByClassName('post-intros')[0]
      if (postIntros) {
        postIntros.classList.add('post-fade-in');
      }
    }
  }

  // UC不支持跨域，所以直接显示
  function asyncCb(){
    if (browser.versions.uc) {
      console.log("UCBrowser");
      fontLoaded();
    } else {
      WebFont.load({
        custom: {
          families: ['Oswald-Regular']
        },
        loading: function () {  //所有字体开始加载
          // console.log('loading');
        },
        active: function () {  //所有字体已渲染
          fontLoaded();
        },
        inactive: function () { //字体预加载失败，无效字体或浏览器不支持加载
          console.log('inactive: timeout');
          fontLoaded();
        },
        timeout: 5000 // Set the timeout to two seconds
      });
    }
  }

  function asyncErr(){
    console.warn('script load from CDN failed, will load local script')
  }

  // load webfont-loader async, and add callback function
  function async(u, cb, err) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (cb) { o.addEventListener('load', function (e) { cb(null, e); }, false); }
    if (err) { o.addEventListener('error', function (e) { err(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }

  var asyncLoadWithFallBack = function(arr, success, reject) {
      var currReject = function(){
        reject()
        arr.shift()
        if(arr.length)
          async(arr[0], success, currReject)
        }

      async(arr[0], success, currReject)
  }

  asyncLoadWithFallBack([
    "https://cdn.jsdelivr.net/npm/webfontloader@1.6.28/webfontloader.min.js", 
    "https://cdn.bootcss.com/webfont/1.6.28/webfontloader.js",
    "/lib/webfontloader.min.js"
  ], asyncCb, asyncErr)
</script>        
        <img class="loading" src="/assets/loading.svg" style="display: block; margin: 6rem auto 0 auto; width: 6rem; height: 6rem;" />
        <div class="container container-unloaded">
            <main class="main post-page">
    <article class="article-entry">
        <p>Java调用C/C++在Java语言里面本来就有的，并非Android独有的，即JNI。JNI就是Java调用C++的规范。</p>
<a id="more"></a>
<h1 id="JNI-概述"><a href="#JNI-概述" class="headerlink" title="JNI 概述"></a>JNI 概述</h1><p>JNI，全称为Java Native Interface，即Java本地接口，JNI是Java调用Native语言的一种特性，通过JNI可以使JAVA和 C/C++进行交互。<br>Java语言是跨平台的语言，而这跨平台的背后都是依靠Java虚拟机，虚拟机采用C/C++编写，适配各个系统，通过JNI为上层Java提供各种服务，保证跨平台性。<br>在Java语言出现前，就有很多程序和库都是由Native语言写的，如果想重复利用这些库，就可以所使用JNI来实现。在Android平台上，JNI就是一座将Java世界和Native世界联通的一座桥梁。<br><img src="https://s2.ax1x.com/2019/08/30/mOgNGD.png" alt="jni.png"><br>通过JNI，Java世界和Native世界的代码就可以相互访问了。</p>
<h1 id="JNI实例：Camera"><a href="#JNI实例：Camera" class="headerlink" title="JNI实例：Camera"></a>JNI实例：Camera</h1><p>最新有在看系统的Camera相关，所以从系统Camera角度来分析下JNI的应用，下面讲的实例基于Camera2</p>
<blockquote>
<p>Android5.0(21)之后android.hardware.Camera就被废弃了，取而代之的是全新的android.hardware.Camera2</p>
</blockquote>
<p>相关代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">frameworks/base/core/jni/AndroidRuntime.cpp</span><br><span class="line"></span><br><span class="line">frameworks/base/core/java/android/hardware/camera2/impl/CameraMetadataNative.java</span><br><span class="line">frameworks/base/core/jni/android_hardware_camera2_CameraMetadata.cpp</span><br></pre></td></tr></table></figure>

<p>Camera2 Java层对应的是CameraMetadataNative.java，Native层对应的是android_hardware_camera2_CameraMetadata.cpp</p>
<h2 id="Java层CameraMetadataNative"><a href="#Java层CameraMetadataNative" class="headerlink" title="Java层CameraMetadataNative"></a>Java层CameraMetadataNative</h2><p>相关代码在CameraMetadataNative.java<br>Camera2使用CameraManager(摄像头管理器)进行控制，CameraManager具体的操作会通过CameraMetadataNative来执行。<br>CameraMetadataNative的初始化</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CameraMetadataNative</span> <span class="keyword">implements</span> <span class="title">Parcelable</span></span></span><br><span class="line"><span class="class">   <span class="title">static</span> </span>&#123;</span><br><span class="line">      <span class="comment">/*</span></span><br><span class="line"><span class="comment">      * We use a class initializer to allow the native code to cache some field offsets</span></span><br><span class="line"><span class="comment">      */</span></span><br><span class="line">      nativeClassInit();</span><br><span class="line">      registerAllMarshalers();</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">native</span> <span class="keyword">void</span> <span class="title">nativeClassInit</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>静态方法初始化调用了Native层的方法<code>nativeClassInit</code>，这个方法对应的Native层具体实现，是在android_hardware_camera2_CameraMetadata.cpp</p>
<h2 id="Native层CameraMetadata"><a href="#Native层CameraMetadata" class="headerlink" title="Native层CameraMetadata"></a>Native层CameraMetadata</h2><p>Native层相关代码在android_hardware_camera2_CameraMetadata.cpp<br>Native方法初始化</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> JNINativeMethod gCameraMetadataMethods[] = &#123;</span><br><span class="line"><span class="comment">// static methods</span></span><br><span class="line">  &#123; <span class="string">"nativeClassInit"</span>,</span><br><span class="line">    <span class="string">"()V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_classInit &#125;,   <span class="comment">//和Java层nativeClassInit()对应</span></span><br><span class="line">  &#123; <span class="string">"nativeGetAllVendorKeys"</span>,</span><br><span class="line">    <span class="string">"(Ljava/lang/Class;)Ljava/util/ArrayList;"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_getAllVendorKeys&#125;,</span><br><span class="line">  &#123; <span class="string">"nativeGetTagFromKey"</span>,</span><br><span class="line">    <span class="string">"(Ljava/lang/String;)I"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_getTagFromKey &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeGetTypeFromTag"</span>,</span><br><span class="line">    <span class="string">"(I)I"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_getTypeFromTag &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeSetupGlobalVendorTagDescriptor"</span>,</span><br><span class="line">    <span class="string">"()I"</span>,</span><br><span class="line">    (<span class="keyword">void</span>*)CameraMetadata_setupGlobalVendorTagDescriptor &#125;,</span><br><span class="line"><span class="comment">// instance methods</span></span><br><span class="line">  &#123; <span class="string">"nativeAllocate"</span>,</span><br><span class="line">    <span class="string">"()J"</span>,</span><br><span class="line">    (<span class="keyword">void</span>*)CameraMetadata_allocate &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeAllocateCopy"</span>,</span><br><span class="line">    <span class="string">"(L"</span> CAMERA_METADATA_CLASS_NAME <span class="string">";)J"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_allocateCopy &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeIsEmpty"</span>,</span><br><span class="line">    <span class="string">"()Z"</span>,</span><br><span class="line">    (<span class="keyword">void</span>*)CameraMetadata_isEmpty &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeGetEntryCount"</span>,</span><br><span class="line">    <span class="string">"()I"</span>,</span><br><span class="line">    (<span class="keyword">void</span>*)CameraMetadata_getEntryCount &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeClose"</span>,</span><br><span class="line">    <span class="string">"()V"</span>,</span><br><span class="line">    (<span class="keyword">void</span>*)CameraMetadata_close &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeSwap"</span>,</span><br><span class="line">    <span class="string">"(L"</span> CAMERA_METADATA_CLASS_NAME <span class="string">";)V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_swap &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeReadValues"</span>,</span><br><span class="line">    <span class="string">"(I)[B"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_readValues &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeWriteValues"</span>,</span><br><span class="line">    <span class="string">"(I[B)V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_writeValues &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeDump"</span>,</span><br><span class="line">    <span class="string">"()V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_dump &#125;,</span><br><span class="line"><span class="comment">// Parcelable interface</span></span><br><span class="line">  &#123; <span class="string">"nativeReadFromParcel"</span>,</span><br><span class="line">    <span class="string">"(Landroid/os/Parcel;)V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_readFromParcel &#125;,</span><br><span class="line">  &#123; <span class="string">"nativeWriteToParcel"</span>,</span><br><span class="line">    <span class="string">"(Landroid/os/Parcel;)V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_writeToParcel &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>gCameraMetadataMethods什么时候会被加载？</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">register_android_hardware_camera2_CameraMetadata</span><span class="params">(JNIEnv *env)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   ......</span><br><span class="line">   <span class="comment">// Register native functions</span></span><br><span class="line">   <span class="keyword">return</span> RegisterMethodsOrDie(env,</span><br><span class="line">         CAMERA_METADATA_CLASS_NAME,</span><br><span class="line">         gCameraMetadataMethods,</span><br><span class="line">         NELEM(gCameraMetadataMethods));</span><br><span class="line">&#125;</span><br><span class="line">......</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">inline</span> <span class="keyword">int</span> <span class="title">RegisterMethodsOrDie</span><span class="params">(JNIEnv* env, <span class="keyword">const</span> <span class="keyword">char</span>* className,</span></span></span><br><span class="line"><span class="function"><span class="params">                                       <span class="keyword">const</span> JNINativeMethod* gMethods, <span class="keyword">int</span> numMethods)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> res = AndroidRuntime::registerNativeMethods(env, className, gMethods, numMethods);</span><br><span class="line">    LOG_ALWAYS_FATAL_IF(res &lt; <span class="number">0</span>, <span class="string">"Unable to register native methods."</span>);</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>register_android_hardware_camera2_CameraMetadata</code>何时会被调用到，这个就需要了解下JNI的查找方式。</p>
<h2 id="JNI查找方式"><a href="#JNI查找方式" class="headerlink" title="JNI查找方式"></a>JNI查找方式</h2><blockquote>
<p>Android系统在启动启动过程中，先启动Kernel创建init进程，紧接着由init进程fork第一个横穿Java和C/C++的进程，即Zygote进程。Zygote启动过程中会AndroidRuntime.cpp中的startVm创建虚拟机，VM创建完成后，紧接着调用startReg完成虚拟机中的JNI方法注册。  </p>
</blockquote>
<p>刚才CameraMetadata中<code>register_android_hardware_camera2_CameraMetadata</code>方法，在AndroidRuntime.cpp的声明：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">extern</span> <span class="keyword">int</span> <span class="title">register_android_hardware_camera2_CameraMetadata</span><span class="params">(JNIEnv *env)</span></span>;</span><br></pre></td></tr></table></figure>

<p>然后在gRegJNI中的静态声明</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> RegJNIRec gRegJNI[] = &#123;</span><br><span class="line">    ......</span><br><span class="line">    REG_JNI(register_android_hardware_camera2_CameraMetadata),</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>gRegJNI方法在startReg中被调用</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*static*/</span> <span class="keyword">int</span> AndroidRuntime::startReg(JNIEnv* env)</span><br><span class="line">&#123;</span><br><span class="line">    ATRACE_NAME(<span class="string">"RegisterAndroidNatives"</span>);</span><br><span class="line">    androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc);</span><br><span class="line">    ALOGV(<span class="string">"--- registering native functions ---\n"</span>);</span><br><span class="line">  </span><br><span class="line">    env-&gt;PushLocalFrame(<span class="number">200</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) &lt; <span class="number">0</span>) &#123;</span><br><span class="line">        env-&gt;PopLocalFrame(<span class="literal">NULL</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    env-&gt;PopLocalFrame(<span class="literal">NULL</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//createJavaThread("fubar", quickTest, (void*) "hello");</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>register_jni_procs(gRegJNI, NELEM(gRegJNI), env)会循环调用gRegJNI数组成员所对应的方法</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">int</span> <span class="title">register_jni_procs</span><span class="params">(<span class="keyword">const</span> RegJNIRec <span class="built_in">array</span>[], <span class="keyword">size_t</span> count, JNIEnv* env)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">size_t</span> i = <span class="number">0</span>; i &lt; count; i++) &#123;</span><br><span class="line">        <span class="keyword">if</span> (<span class="built_in">array</span>[i].mProc(env) &lt; <span class="number">0</span>) &#123;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> NDEBUG</span></span><br><span class="line">            ALOGD(<span class="string">"----------!!! %s failed to load\n"</span>, <span class="built_in">array</span>[i].mName);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>这样android_hardware_camera2_CameraMetadata.cpp中的<code>int register_android_hardware_camera2_CameraMetadata(JNIEnv *env)</code>就会被调用到。<br>除了这种Android系统启动时，就注册JNI所对应的方法。还有一种就是程序自定义的JNI方法，以 MediePlay 为例：<br>相关代码路径</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">frameworks/base/media/java/android/media/MediaPlayer.java</span><br><span class="line">frameworks/base/media/jni/android_media_MediaPlayer.cpp</span><br></pre></td></tr></table></figure>

<p>MediaPlayer声明：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MediaPlayer</span> <span class="keyword">extends</span> <span class="title">PlayerBase</span></span></span><br><span class="line"><span class="class">                         <span class="keyword">implements</span> <span class="title">SubtitleController</span>.<span class="title">Listener</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">   ......</span><br><span class="line">   <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">native</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">native_init</span><span class="params">()</span></span>;</span><br><span class="line">   ......</span><br><span class="line">   <span class="keyword">static</span> &#123;</span><br><span class="line">      System.loadLibrary(<span class="string">"media_jni"</span>);</span><br><span class="line">      native_init();</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>静态代码块中使用System.loadLibrary加载动态库，media_jni在Android平台对应的是libmedia_jni.so库。<br>在jni目录<code>/frameworks/base/media/jni/Android.mk</code>中有相应的声明：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">LOCAL_SRC_FILES:= \</span><br><span class="line">android_media_MediaPlayer.cpp \</span><br><span class="line">...</span><br><span class="line">LOCAL_MODULE:= libmedia_jni</span><br></pre></td></tr></table></figure>

<p>在<code>android_media_MediaPlayer.cpp</code>找到对应的Native(natvie_init)方法：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">void</span></span><br><span class="line">android_media_MediaPlayer_native_init(JNIEnv *env)</span><br><span class="line">&#123;</span><br><span class="line">    jclass clazz;</span><br><span class="line"></span><br><span class="line">    clazz = env-&gt;FindClass(<span class="string">"android/media/MediaPlayer"</span>);</span><br><span class="line">    <span class="keyword">if</span> (clazz == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>JNI注册的方法就是上面描述的两种方法：</p>
<ul>
<li>在Android系统启动时注册，在AndroidRuntime.cpp中的gRegJNI方法中声明</li>
<li>使用System.loadLibrary()方式注册</li>
</ul>
<h1 id="JNI基础"><a href="#JNI基础" class="headerlink" title="JNI基础"></a>JNI基础</h1><p>上面一节主要描述了系统中Java层和Native层交互和实现，并没有对JNI的基础理论，流程进行分析</p>
<h2 id="JNI命名规则"><a href="#JNI命名规则" class="headerlink" title="JNI命名规则"></a>JNI命名规则</h2><p>JNI方法名规范 :</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">返回值 + Java前缀 + 全路径类名 + 方法名 + 参数① JNIEnv + 参数② jobject + 其它参数</span><br></pre></td></tr></table></figure>

<p>简单的一个例子，返回一个字符串</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">extern</span> <span class="string">"C"</span> JNIEXPORT jstring JNICALL</span><br><span class="line">Java_com_yeungeek_jnisample_NativeHelper_stringFromJNI(JNIEnv *env, jclass jclass1) &#123;</span><br><span class="line">    LOGD(<span class="string">"##### from c"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> env-&gt;NewStringUTF(<span class="string">"Hello JNI"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>返回值：jstring</li>
<li>全路径类名：com_yeungeek_jnisample_NativeHelper</li>
<li>方法名：stringFromJNI</li>
</ul>
<h2 id="JNI开发流程"><a href="#JNI开发流程" class="headerlink" title="JNI开发流程"></a>JNI开发流程</h2><ul>
<li>在Java中先声明一个native方法</li>
<li>编译Java源文件javac得到.class文件</li>
<li>通过javah -jni命令导出JNI的.h头文件</li>
<li>使用Java需要交互的本地代码，实现在Java中声明的Native方法（如果Java需要与C++交互，那么就用C++实现Java的Native方法。）</li>
<li>将本地代码编译成动态库(Windows系统下是.dll文件，如果是Linux系统下是.so文件，如果是Mac系统下是.jnilib)</li>
<li>通过Java命令执行Java程序，最终实现Java调用本地代码。</li>
</ul>
<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><h3 id="基本数据类型"><a href="#基本数据类型" class="headerlink" title="基本数据类型"></a>基本数据类型</h3><table>
<thead>
<tr>
<th align="left">Signature</th>
<th align="left">Java</th>
<th align="left">Native</th>
</tr>
</thead>
<tbody><tr>
<td align="left">B</td>
<td align="left">byte</td>
<td align="left">jbyte</td>
</tr>
<tr>
<td align="left">C</td>
<td align="left">char</td>
<td align="left">jchar</td>
</tr>
<tr>
<td align="left">D</td>
<td align="left">double</td>
<td align="left">jdouble</td>
</tr>
<tr>
<td align="left">F</td>
<td align="left">float</td>
<td align="left">jfloat</td>
</tr>
<tr>
<td align="left">I</td>
<td align="left">int</td>
<td align="left">jint</td>
</tr>
<tr>
<td align="left">S</td>
<td align="left">short</td>
<td align="left">jshort</td>
</tr>
<tr>
<td align="left">J</td>
<td align="left">long</td>
<td align="left">jlong</td>
</tr>
<tr>
<td align="left">Z</td>
<td align="left">boolean</td>
<td align="left">jboolean</td>
</tr>
<tr>
<td align="left">V</td>
<td align="left">void</td>
<td align="left">jvoid</td>
</tr>
</tbody></table>
<h3 id="引用数据类型"><a href="#引用数据类型" class="headerlink" title="引用数据类型"></a>引用数据类型</h3><table>
<thead>
<tr>
<th align="left">Signature</th>
<th align="left">Java</th>
<th align="left">Native</th>
</tr>
</thead>
<tbody><tr>
<td align="left">L+classname +;</td>
<td align="left">Object</td>
<td align="left">jobject</td>
</tr>
<tr>
<td align="left">Ljava/lang/String;</td>
<td align="left">String</td>
<td align="left">jstring</td>
</tr>
<tr>
<td align="left">[L+classname +;</td>
<td align="left">Object[]</td>
<td align="left">jobjectArray</td>
</tr>
<tr>
<td align="left">Ljava.lang.Class;</td>
<td align="left">Class</td>
<td align="left">jclass</td>
</tr>
<tr>
<td align="left">Ljava.lang.Throwable;</td>
<td align="left">Throwable</td>
<td align="left">jthrowable</td>
</tr>
<tr>
<td align="left">[B</td>
<td align="left">byte[]</td>
<td align="left">jbyteArray</td>
</tr>
<tr>
<td align="left">[C</td>
<td align="left">char[]</td>
<td align="left">jcharArray</td>
</tr>
<tr>
<td align="left">[D</td>
<td align="left">double[]</td>
<td align="left">jdoubleArray</td>
</tr>
<tr>
<td align="left">[F</td>
<td align="left">float[]</td>
<td align="left">jfloatArray</td>
</tr>
<tr>
<td align="left">[I</td>
<td align="left">int[]</td>
<td align="left">jintArray</td>
</tr>
<tr>
<td align="left">[S</td>
<td align="left">short[]</td>
<td align="left">jshortArray</td>
</tr>
<tr>
<td align="left">[J</td>
<td align="left">long[]</td>
<td align="left">jlongArray</td>
</tr>
<tr>
<td align="left">[Z</td>
<td align="left">boolean[]</td>
<td align="left">jbooleanArray</td>
</tr>
</tbody></table>
<h2 id="方法签名"><a href="#方法签名" class="headerlink" title="方法签名"></a>方法签名</h2><p>JNI的方法签名的格式：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(参数签名格式...)返回值签名格式</span><br></pre></td></tr></table></figure>

<p>demo的native 方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">native</span> java.lang.<span class="function">String <span class="title">stringFromJNI</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>

<p>可以通过javap命令生成方法签名``：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">()Ljava/lang/String;</span><br></pre></td></tr></table></figure>

<h1 id="JNI原理"><a href="#JNI原理" class="headerlink" title="JNI原理"></a>JNI原理</h1><p>Java语言的执行环境是Java虚拟机(JVM)，JVM其实是主机环境中的一个进程，每个JVM虚拟机都在本地环境中有一个JavaVM结构体，该结构体在创建Java虚拟机时被返回，在JNI环境中创建JVM的函数为JNI_CreateJavaVM。<br>JNI 定义了两个关键数据结构，即“JavaVM”和“JNIEnv”，两者本质上都是指向函数表的二级指针。</p>
<h2 id="JavaVM"><a href="#JavaVM" class="headerlink" title="JavaVM"></a>JavaVM</h2><p>JavaVM是Java虚拟机在JNI层的代表，JavaVM 提供了“调用接口”函数，您可以利用此类函数创建和销毁 JavaVM。理论上，每个进程可以包含多个JavaVM，但AnAndroid只允许每个进程包含一个JavaVM。</p>
<h2 id="JNIEnv"><a href="#JNIEnv" class="headerlink" title="JNIEnv"></a>JNIEnv</h2><p>JNIEnv是一个线程相关的结构体，该结构体代表了Java在本线程的执行环境。JNIEnv 提供了大多数 JNI 函数。您的原生函数均会接收 JNIEnv 作为第一个参数。<br>JNIEnv作用：</p>
<ul>
<li>调用Java函数</li>
<li>操作Java代码</li>
</ul>
<p>JNIEnv定义(jni.h)：<br><code>libnativehelper/include/nativehelper/jni.h</code></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">if</span> defined(__cplusplus)</span></span><br><span class="line"><span class="keyword">typedef</span> _JNIEnv JNIEnv;</span><br><span class="line"><span class="keyword">typedef</span> _JavaVM JavaVM; </span><br><span class="line"><span class="meta">#<span class="meta-keyword">else</span></span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">const</span> <span class="class"><span class="keyword">struct</span> <span class="title">JNINativeInterface</span>* <span class="title">JNIEnv</span>;</span></span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">const</span> <span class="class"><span class="keyword">struct</span> <span class="title">JNIInvokeInterface</span>* <span class="title">JavaVM</span>;</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br></pre></td></tr></table></figure>

<p>定义中可以看到JavaVM，Android中一个进程只会有一个JavaVM，一个JVM对应一个JavaVM结构，而一个JVM中可能创建多个Java线程，每个线程对应一个JNIEnv结构<br><img src="https://s2.ax1x.com/2019/09/01/n9wYL9.png" alt="javavm.png"></p>
<h2 id="注册JNI函数"><a href="#注册JNI函数" class="headerlink" title="注册JNI函数"></a>注册JNI函数</h2><p>Java世界和Native世界的方法是如何关联的，就是通过JNI函数注册来实现。JNI函数注册有两种方式：</p>
<h3 id="静态注册"><a href="#静态注册" class="headerlink" title="静态注册"></a>静态注册</h3><p>这种方法就是通过函数名来找对应的JNI函数，可以通过<code>javah</code>命令行来生成JNI头文件</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">javah com.yeungeek.jnisample.NativeHelper</span><br></pre></td></tr></table></figure>

<p>生成对应的<code>com_yeungeek_jnisample_NativeHelper.h</code>文件，生成对应的JNI函数，然后在实现这个函数就可以了</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * Class:     com_yeungeek_jnisample_NativeHelper</span></span><br><span class="line"><span class="comment"> * Method:    stringFromJNI</span></span><br><span class="line"><span class="comment"> * Signature: ()Ljava/lang/String;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">JNIEXPORT jstring JNICALL Java_com_yeungeek_jnisample_NativeHelper_stringFromJNI</span><br><span class="line">  (JNIEnv *, jclass);</span><br></pre></td></tr></table></figure>

<p>静态注册方法中，Native是如何找到对应的JNI函数，在<a href="#JNI查找方式">JNI查找方式</a>中介绍系统的流程，并没有详细说明静态注册的查找。这里简单说明下这个过程(以上面的声明为例子s)：<br>当Java调用native stringFromJNI函数时，会从对应JNI库中查找<code>Java_com_yeungeek_jnisample_NativeHelper_stringFromJNI</code>函数，如果没有找到，就会报错。<br>静态注册方法，就是根据函数名来关联Java函数和JNI函数，JNI函数需要遵循特定的格式，这其中就有一些缺点：</p>
<ul>
<li>声明了native方法的Java类，需要通过<code>javah</code>来生成头文件</li>
<li>JNI函数名称非常长</li>
<li>第一次调用native函数，需要通过函数名来搜索关联对应的JNI函数，效率比较低</li>
</ul>
<p>如何解决这些问题，让native函数，提前知道JNI函数，就可以解决这个问题，这个过程就是动态注册。</p>
<h3 id="动态注册"><a href="#动态注册" class="headerlink" title="动态注册"></a>动态注册</h3><p>动态注册在前面的Camera例子中，已经有涉及到，JNI函数<code>classInit</code>的声明。</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">static</span> <span class="keyword">const</span> JNINativeMethod gCameraMetadataMethods[] = &#123;</span><br><span class="line"><span class="comment">// static methods</span></span><br><span class="line">  &#123; <span class="string">"nativeClassInit"</span>,</span><br><span class="line">    <span class="string">"()V"</span>,</span><br><span class="line">    (<span class="keyword">void</span> *)CameraMetadata_classInit &#125;,   <span class="comment">//和Java层nativeClassInit()对应</span></span><br><span class="line">   ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>JNI中有一种结构用来记录Java的Native方法和JNI方法的关联关系，它就是JNINativeMethod，它在jni.h中被定义：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">char</span>* name;  <span class="comment">//Java层native函数名</span></span><br><span class="line">    <span class="keyword">const</span> <span class="keyword">char</span>* signature; <span class="comment">//Java函数签名，记录参数类型和个数，以及返回值类型</span></span><br><span class="line">    <span class="keyword">void</span>*       fnPtr; <span class="comment">//Native层对应的函数指针</span></span><br><span class="line">&#125; JNINativeMethod;</span><br></pre></td></tr></table></figure>

<p>在<a href="#JNI查找方式">JNI查找方式</a>说到，JNI注册的两种时间，第一种已经介绍过了，我们自定义的native函数，基本都是会使用<code>System.loadLibrary(“xxx”)</code>，来进行JNI函数的关联。</p>
<h4 id="loadLibrary-Android7-0"><a href="#loadLibrary-Android7-0" class="headerlink" title="loadLibrary(Android7.0)"></a>loadLibrary(Android7.0)</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">loadLibrary</span><span class="params">(String libname)</span> </span>&#123;</span><br><span class="line">   Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), libname);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用到Runtime(libcore/ojluni/src/main/java/java/lang/Runtime.java)的loadLibrary0方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">loadLibrary0</span><span class="params">(ClassLoader loader, String libname)</span> </span>&#123;</span><br><span class="line">   ......</span><br><span class="line">   String libraryName = libname;</span><br><span class="line">   <span class="keyword">if</span> (loader != <span class="keyword">null</span>) &#123;</span><br><span class="line">      String filename = loader.findLibrary(libraryName);</span><br><span class="line">      <span class="keyword">if</span> (filename == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// It's not necessarily true that the ClassLoader used</span></span><br><span class="line">            <span class="comment">// System.mapLibraryName, but the default setup does, and it's</span></span><br><span class="line">            <span class="comment">// misleading to say we didn't find "libMyLibrary.so" when we</span></span><br><span class="line">            <span class="comment">// actually searched for "liblibMyLibrary.so.so".</span></span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UnsatisfiedLinkError(loader + <span class="string">" couldn't find \""</span> +</span><br><span class="line">                                          System.mapLibraryName(libraryName) + <span class="string">"\""</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//doLoad</span></span><br><span class="line">      String error = doLoad(filename, loader);</span><br><span class="line">      <span class="keyword">if</span> (error != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> UnsatisfiedLinkError(error);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span>;</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="comment">//loader 为 null</span></span><br><span class="line">   ......</span><br><span class="line">   <span class="keyword">for</span> (String directory : getLibPaths()) &#123;</span><br><span class="line">      String candidate = directory + filename;</span><br><span class="line">      candidates.add(candidate);</span><br><span class="line"></span><br><span class="line">      <span class="keyword">if</span> (IoUtils.canOpenReadOnly(candidate)) &#123;</span><br><span class="line">            String error = doLoad(candidate, loader);</span><br><span class="line">            <span class="keyword">if</span> (error == <span class="keyword">null</span>) &#123;</span><br><span class="line">               <span class="keyword">return</span>; <span class="comment">// We successfully loaded the library. Job done.</span></span><br><span class="line">            &#125;</span><br><span class="line">            lastError = error;</span><br><span class="line">      &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="doLoad"><a href="#doLoad" class="headerlink" title="doLoad"></a>doLoad</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> String <span class="title">doLoad</span><span class="params">(String name, ClassLoader loader)</span> </span>&#123;</span><br><span class="line">   <span class="comment">//调用 native 方法</span></span><br><span class="line">   <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> nativeLoad(name, loader, librarySearchPath);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="nativeLoad"><a href="#nativeLoad" class="headerlink" title="nativeLoad"></a>nativeLoad</h4><p>进入到虚拟机代码<code>/libcore/ojluni/src/main/native/Runtime.c</code></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">JNIEXPORT jstring JNICALL</span><br><span class="line">Runtime_nativeLoad(JNIEnv* env, jclass ignored, jstring javaFilename,</span><br><span class="line">                   jobject javaLoader, jstring javaLibrarySearchPath)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">return</span> JVM_NativeLoad(env, javaFilename, javaLoader, javaLibrarySearchPath);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>然后调用<code>JVM_NativeLoad</code>，JVM_NativeLoad方法申明在jvm.h中，实现在<code>OpenjdkJvm.cc(/art/runtime/openjdkjvm/OpenjdkJvm.cc)</code></p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">JNIEXPORT jstring <span class="title">JVM_NativeLoad</span><span class="params">(JNIEnv* env,</span></span></span><br><span class="line"><span class="function"><span class="params">                                 jstring javaFilename,</span></span></span><br><span class="line"><span class="function"><span class="params">                                 jobject javaLoader,</span></span></span><br><span class="line"><span class="function"><span class="params">                                 jstring javaLibrarySearchPath)</span> </span>&#123;</span><br><span class="line">  <span class="function">ScopedUtfChars <span class="title">filename</span><span class="params">(env, javaFilename)</span></span>;</span><br><span class="line">  <span class="keyword">if</span> (filename.c_str() == <span class="literal">NULL</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">NULL</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">std</span>::<span class="built_in">string</span> error_msg;</span><br><span class="line">  &#123;</span><br><span class="line">    art::JavaVMExt* vm = art::Runtime::Current()-&gt;GetJavaVM();</span><br><span class="line">    <span class="keyword">bool</span> success = vm-&gt;LoadNativeLibrary(env,</span><br><span class="line">                                         filename.c_str(),</span><br><span class="line">                                         javaLoader,</span><br><span class="line">                                         javaLibrarySearchPath,</span><br><span class="line">                                         &amp;error_msg);</span><br><span class="line">    <span class="keyword">if</span> (success) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">nullptr</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Don't let a pending exception from JNI_OnLoad cause a CheckJNI issue with NewStringUTF.</span></span><br><span class="line">  env-&gt;ExceptionClear();</span><br><span class="line">  <span class="keyword">return</span> env-&gt;NewStringUTF(error_msg.c_str());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="LoadNativeLibrary"><a href="#LoadNativeLibrary" class="headerlink" title="LoadNativeLibrary"></a>LoadNativeLibrary</h4><p>调用JavaVMExt的LoadNativeLibrary方法，方法在(art/runtime/java_vm_ext.cc)中，这个方法代码非常多，选取主要的部分进行分析</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">bool</span> JavaVMExt::LoadNativeLibrary(JNIEnv* env,</span><br><span class="line">                                  <span class="keyword">const</span> <span class="built_in">std</span>::<span class="built_in">string</span>&amp; path,</span><br><span class="line">                                  jobject class_loader,</span><br><span class="line">                                  jstring library_path,</span><br><span class="line">                                  <span class="built_in">std</span>::<span class="built_in">string</span>* error_msg) &#123;</span><br><span class="line">         ......</span><br><span class="line">         <span class="keyword">bool</span> was_successful = <span class="literal">false</span>;</span><br><span class="line">         <span class="comment">//加载so库中查找JNI_OnLoad方法，如果没有系统就认为是静态注册方式进行的，直接返回true，代表so库加载成功，</span></span><br><span class="line">         <span class="comment">//如果找到JNI_OnLoad就会调用JNI_OnLoad方法，JNI_OnLoad方法中一般存放的是方法注册的函数，</span></span><br><span class="line">         <span class="comment">//所以如果采用动态注册就必须要实现JNI_OnLoad方法，否则调用java中申明的native方法时会抛出异常</span></span><br><span class="line">         <span class="keyword">void</span>* sym = library-&gt;FindSymbol(<span class="string">"JNI_OnLoad"</span>, <span class="literal">nullptr</span>);</span><br><span class="line">         <span class="keyword">if</span> (sym == <span class="literal">nullptr</span>) &#123;</span><br><span class="line">            VLOG(jni) &lt;&lt; <span class="string">"[No JNI_OnLoad found in \""</span> &lt;&lt; path &lt;&lt; <span class="string">"\"]"</span>;</span><br><span class="line">            was_successful = <span class="literal">true</span>;</span><br><span class="line">         &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// Call JNI_OnLoad.  We have to override the current class</span></span><br><span class="line">            <span class="comment">// loader, which will always be "null" since the stuff at the</span></span><br><span class="line">            <span class="comment">// top of the stack is around Runtime.loadLibrary().  (See</span></span><br><span class="line">            <span class="comment">// the comments in the JNI FindClass function.)</span></span><br><span class="line">            ScopedLocalRef&lt;jobject&gt; old_class_loader(env, env-&gt;NewLocalRef(self-&gt;GetClassLoaderOverride()));</span><br><span class="line">            self-&gt;SetClassLoaderOverride(class_loader);</span><br><span class="line"></span><br><span class="line">            VLOG(jni) &lt;&lt; <span class="string">"[Calling JNI_OnLoad in \""</span> &lt;&lt; path &lt;&lt; <span class="string">"\"]"</span>;</span><br><span class="line">            <span class="function"><span class="keyword">typedef</span> <span class="title">int</span> <span class="params">(*JNI_OnLoadFn)</span><span class="params">(JavaVM*, <span class="keyword">void</span>*)</span></span>;</span><br><span class="line">            JNI_OnLoadFn jni_on_load = <span class="keyword">reinterpret_cast</span>&lt;JNI_OnLoadFn&gt;(sym);</span><br><span class="line">            <span class="comment">//调用JNI_OnLoad方法</span></span><br><span class="line">            <span class="keyword">int</span> version = (*jni_on_load)(<span class="keyword">this</span>, <span class="literal">nullptr</span>);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (runtime_-&gt;GetTargetSdkVersion() != <span class="number">0</span> &amp;&amp; runtime_-&gt;GetTargetSdkVersion() &lt;= <span class="number">21</span>) &#123;</span><br><span class="line">               <span class="comment">// Make sure that sigchain owns SIGSEGV.</span></span><br><span class="line">               EnsureFrontOfChain(SIGSEGV);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            self-&gt;SetClassLoaderOverride(old_class_loader.get());</span><br><span class="line">         &#125;</span><br><span class="line">         ......</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>代码里的主要逻辑：</p>
<ul>
<li>加载so库中查找JNI_OnLoad方法，如果没有系统就认为是静态注册方式进行的，直接返回true，代表so库加载成功</li>
<li>如果找到JNI_OnLoad就会调用JNI_OnLoad方法，JNI_OnLoad方法中一般存放的是方法注册的函数</li>
<li>所以如果采用动态注册就必须要实现<code>JNI_OnLoad</code>方法，否则调用Java中的native方法时会抛出异常</li>
</ul>
<h2 id="jclass、jmethodID和jfieldID"><a href="#jclass、jmethodID和jfieldID" class="headerlink" title="jclass、jmethodID和jfieldID"></a>jclass、jmethodID和jfieldID</h2><p>如果要通过原生代码访问对象的字段，需要执行以下操作：</p>
<ol>
<li>使用 FindClass 获取类的类对象引用</li>
<li>使用 GetFieldID 获取字段的字段 ID</li>
<li>使用适当内容获取字段的内容，例如 GetIntField</li>
</ol>
<p>具体的使用，放在第二篇文章中讲解</p>
<h2 id="JNI的引用"><a href="#JNI的引用" class="headerlink" title="JNI的引用"></a>JNI的引用</h2><p>JNI规范中定义了三种引用：</p>
<ul>
<li>局部引用（Local Reference）</li>
<li>全局引用（Global Reference）</li>
<li>弱全局引用（Weak Global Reference）</li>
</ul>
<h3 id="局部引用"><a href="#局部引用" class="headerlink" title="局部引用"></a>局部引用</h3><p>也叫本地引用，在 JNI层函数使用的非全局引用对象都是Local Reference，最大的特点就是，JNI 函数返回后，这些声明的引用可能就会被垃圾回收</p>
<h3 id="全局引用"><a href="#全局引用" class="headerlink" title="全局引用"></a>全局引用</h3><p>这种声明的对象，不会主动释放资源，不会被垃圾回收</p>
<h3 id="弱全局引用"><a href="#弱全局引用" class="headerlink" title="弱全局引用"></a>弱全局引用</h3><p>一种特殊的全局引用，在运行过程中可能被回收，使用之前需要判断下是否为空</p>
<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li><a href="https://juejin.im/post/59827fb86fb9a03c341907e6" target="_blank" rel="noopener">Android：清晰讲解JNI 与 NDK（含实例教学）</a></li>
<li><a href="https://www.jianshu.com/nb/22528035" target="_blank" rel="noopener">Android JNI学习</a></li>
<li><a href="http://gityuan.com/2016/05/28/android-jni/" target="_blank" rel="noopener">Android JNI原理分析</a></li>
<li><a href="http://liuwangshu.cn/framework/jni/1-mediarecorder_register.html" target="_blank" rel="noopener">Android深入理解JNI（一）JNI原理与静态、动态注册</a></li>
<li><a href="https://developer.android.com/training/articles/perf-jni" target="_blank" rel="noopener">JNI Tips</a></li>
</ul>

    </article>
    <!-- license  -->
    
        <div class="license-wrapper">
            <p>原文作者：<a href="http://yeungeek.github.io">Yeungeek</a>
            </p><p>原文链接：<a href="http://yeungeek.github.io/2019/08/21/AndroidNDK-DeepUnderstandJNI/">http://yeungeek.github.io/2019/08/21/AndroidNDK-DeepUnderstandJNI/</a>
            </p><p>发表日期：<a href="http://yeungeek.github.io/2019/08/21/AndroidNDK-DeepUnderstandJNI/">August 21st 2019, 11:21:43 am</a>
            </p><p>更新日期：<a href="http://yeungeek.github.io/2019/08/21/AndroidNDK-DeepUnderstandJNI/">January 17th 2020, 3:44:17 am</a>
            </p><p>版权声明：本文采用<a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/">知识共享署名-非商业性使用 4.0 国际许可协议</a>进行许可</p>
        </div>
    
    <!-- paginator  -->
    <ul class="post-paginator">
        <li class="next">
            
                <div class="nextSlogan">Next Post</div>
                <a href="/2020/01/13/AndroidCamera-Series/" title="Android Camera-系列文章">
                    <div class="nextTitle">Android Camera-系列文章</div>
                </a>
            
        </li>
        <li class="previous">
            
                <div class="prevSlogan">Previous Post</div>
                <a href="/2019/07/25/Network-Retrofit/" title="Android网络编程-Retrofit源码角度分析Http">
                    <div class="prevTitle">Android网络编程-Retrofit源码角度分析Http</div>
                </a>
            
        </li>
    </ul>
    <!-- 评论插件 -->
    <!-- 来必力City版安装代码 -->

    <div id="lv-container" data-id="city" data-uid="MTAyMC8yODIyNi80Nzk4">
        <script type="text/javascript">
            (function (d, s) {
                var j, e = d.getElementsByTagName(s)[0];
                if (typeof LivereTower === 'function') { return; }
                j = d.createElement(s);
                j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
                j.async = true;

                e.parentNode.insertBefore(j, e);
            })(document, 'script');
        </script>
        <noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
    </div>

<!-- City版安装代码已完成 -->
    
    
    <!-- partial('_partial/comment/changyan') -->
    <!--PC版-->


    
    

    <!-- 评论 -->
</main>
            <!-- profile -->
            
        </div>
        <footer class="footer footer-unloaded">
    <!-- social  -->
    
    <div class="social">
        
    
        
            
                <a href="mailto:yeungeek@gmail.com" class="iconfont-archer email" title="email"></a>
            
        
    
        
            
                <a href="//github.com/yeungeek" class="iconfont-archer github" target="_blank" title="github"></a>
            
        
    
        
            
                <span class="iconfont-archer wechat" title="wechat">
                  
                  <img class="profile-qr" src="/assets/wechat_qr.jpeg">
                </span>
            
        
    
        
    
        
    
        
            
                <a href="//weibo.com/springyounger" class="iconfont-archer weibo" target="_blank" title="weibo"></a>
            
        
    
        
    
        
    
        
    
        
            
                <a href="//twitter.com/yeungeek" class="iconfont-archer twitter" target="_blank" title="twitter"></a>
            
        
    
        
    
        
            
                <a href="//stackoverflow.com/users/943667/yeungeek" class="iconfont-archer stack-overflow" target="_blank" title="stack-overflow"></a>
            
        
    
        
            
                <a href="//segmentfault.com/u/yeungeek" class="iconfont-archer segmentFault" target="_blank" title="segmentFault"></a>
            
        
    
        
    
        
    
        
    
        
    
        
    
        
    
        
            
                <a href="/atom.xml" class="iconfont-archer rss" target="_blank" title="rss"></a>
            
        
    

    </div>
    
    <!-- powered by Hexo  -->
    <div class="copyright">
        <span id="hexo-power">Powered by <a href="https://hexo.io/" target="_blank">Hexo</a></span><span class="iconfont-archer power">&#xe635;</span><span id="theme-info">theme <a href="https://github.com/fi3ework/hexo-theme-archer" target="_blank">Archer</a></span>
    </div>
    <!-- 不蒜子  -->
    
    <div class="busuanzi-container">
    
     
    <span id="busuanzi_container_site_pv">PV: <span id="busuanzi_value_site_pv"></span> :)</span>
    
    </div>
    
</footer>
    </div>
    <!-- toc -->
    
    <div class="toc-wrapper" style=
    







top:40vh;

    >
        <div class="toc-catalog">
            <span class="iconfont-archer catalog-icon">&#xe613;</span><span>CATALOG</span>
        </div>
        <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JNI-概述"><span class="toc-number">1.</span> <span class="toc-text">JNI 概述</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JNI实例：Camera"><span class="toc-number">2.</span> <span class="toc-text">JNI实例：Camera</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Java层CameraMetadataNative"><span class="toc-number">2.1.</span> <span class="toc-text">Java层CameraMetadataNative</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Native层CameraMetadata"><span class="toc-number">2.2.</span> <span class="toc-text">Native层CameraMetadata</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JNI查找方式"><span class="toc-number">2.3.</span> <span class="toc-text">JNI查找方式</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JNI基础"><span class="toc-number">3.</span> <span class="toc-text">JNI基础</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JNI命名规则"><span class="toc-number">3.1.</span> <span class="toc-text">JNI命名规则</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JNI开发流程"><span class="toc-number">3.2.</span> <span class="toc-text">JNI开发流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#数据类型"><span class="toc-number">3.3.</span> <span class="toc-text">数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#基本数据类型"><span class="toc-number">3.3.1.</span> <span class="toc-text">基本数据类型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#引用数据类型"><span class="toc-number">3.3.2.</span> <span class="toc-text">引用数据类型</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法签名"><span class="toc-number">3.4.</span> <span class="toc-text">方法签名</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JNI原理"><span class="toc-number">4.</span> <span class="toc-text">JNI原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaVM"><span class="toc-number">4.1.</span> <span class="toc-text">JavaVM</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JNIEnv"><span class="toc-number">4.2.</span> <span class="toc-text">JNIEnv</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#注册JNI函数"><span class="toc-number">4.3.</span> <span class="toc-text">注册JNI函数</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#静态注册"><span class="toc-number">4.3.1.</span> <span class="toc-text">静态注册</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#动态注册"><span class="toc-number">4.3.2.</span> <span class="toc-text">动态注册</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#loadLibrary-Android7-0"><span class="toc-number">4.3.2.1.</span> <span class="toc-text">loadLibrary(Android7.0)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#doLoad"><span class="toc-number">4.3.2.2.</span> <span class="toc-text">doLoad</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#nativeLoad"><span class="toc-number">4.3.2.3.</span> <span class="toc-text">nativeLoad</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#LoadNativeLibrary"><span class="toc-number">4.3.2.4.</span> <span class="toc-text">LoadNativeLibrary</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#jclass、jmethodID和jfieldID"><span class="toc-number">4.4.</span> <span class="toc-text">jclass、jmethodID和jfieldID</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JNI的引用"><span class="toc-number">4.5.</span> <span class="toc-text">JNI的引用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#局部引用"><span class="toc-number">4.5.1.</span> <span class="toc-text">局部引用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#全局引用"><span class="toc-number">4.5.2.</span> <span class="toc-text">全局引用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#弱全局引用"><span class="toc-number">4.5.3.</span> <span class="toc-text">弱全局引用</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#参考"><span class="toc-number">5.</span> <span class="toc-text">参考</span></a></li></ol>
    </div>
    
    <div class="back-top iconfont-archer">&#xe639;</div>
    <div class="sidebar sidebar-hide">
    <ul class="sidebar-tabs sidebar-tabs-active-0">
        <li class="sidebar-tab-archives"><span class="iconfont-archer">&#xe67d;</span><span class="tab-name">Archive</span></li>
        <li class="sidebar-tab-tags"><span class="iconfont-archer">&#xe61b;</span><span class="tab-name">Tag</span></li>
        <li class="sidebar-tab-categories"><span class="iconfont-archer">&#xe666;</span><span class="tab-name">Cate</span></li>
    </ul>
    <div class="sidebar-content sidebar-content-show-archive">
          <div class="sidebar-panel-archives">
    <!-- 在ejs中将archive按照时间排序 -->
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <div class="total-and-search">
        <div class="total-archive">
        Total : 12
        </div>
        <!-- search  -->
        
    </div>
    
    <div class="post-archive">
    
    
    
    
    <div class="archive-year"> 2020 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/17</span><a class="archive-post-title" href="/2020/01/17/AndroidCamera-UsingCamera1/">Android Camera-Camera1使用</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/14</span><a class="archive-post-title" href="/2020/01/14/AndroidCamera-Basic/">Android Camera-基础知识篇</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">01/13</span><a class="archive-post-title" href="/2020/01/13/AndroidCamera-Series/">Android Camera-系列文章</a>
        </li>
    
    
    
    
    
        </ul>
    
    <div class="archive-year"> 2019 </div>
    <ul class="year-list">
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">08/21</span><a class="archive-post-title" href="/2019/08/21/AndroidNDK-DeepUnderstandJNI/">Android NDK-深入理解JNI</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/25</span><a class="archive-post-title" href="/2019/07/25/Network-Retrofit/">Android网络编程-Retrofit源码角度分析Http</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/17</span><a class="archive-post-title" href="/2019/07/17/Network-OKHttp/">Android网络编程-OKHttp源码角度分析Http</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/15</span><a class="archive-post-title" href="/2019/07/15/Network-Cookie-Session-Token/">Android网络编程-Cookie，Session，Token</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">07/12</span><a class="archive-post-title" href="/2019/07/12/Network-Http/">Android网络编程-HTTP/HTTPS</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/26</span><a class="archive-post-title" href="/2019/06/26/Network-Socket/">Android网络编程-Socket</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/21</span><a class="archive-post-title" href="/2019/06/21/Network-TCP-IP/">Android网络编程-TCP/IP协议</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/14</span><a class="archive-post-title" href="/2019/06/14/Network-Basic/">Android网络编程-计算机网络基础</a>
        </li>
    
    
        <li class="archive-post-item">
            <span class="archive-post-date">06/13</span><a class="archive-post-title" href="/2019/06/13/Network-Series/">Android网络编程-系列文章</a>
        </li>
    
    </ul></div>
  </div>
        <div class="sidebar-panel-tags">
    <div class="sidebar-tags-name">
    
        <span class="sidebar-tag-name" data-tags="Camera"><span class="iconfont-archer">&#xe606;</span>Camera</span>
    
        <span class="sidebar-tag-name" data-tags="Camera2"><span class="iconfont-archer">&#xe606;</span>Camera2</span>
    
        <span class="sidebar-tag-name" data-tags="CameraX"><span class="iconfont-archer">&#xe606;</span>CameraX</span>
    
        <span class="sidebar-tag-name" data-tags="JNI"><span class="iconfont-archer">&#xe606;</span>JNI</span>
    
        <span class="sidebar-tag-name" data-tags="NDK"><span class="iconfont-archer">&#xe606;</span>NDK</span>
    
        <span class="sidebar-tag-name" data-tags="Network"><span class="iconfont-archer">&#xe606;</span>Network</span>
    
        <span class="sidebar-tag-name" data-tags="Session"><span class="iconfont-archer">&#xe606;</span>Session</span>
    
        <span class="sidebar-tag-name" data-tags="Cookie"><span class="iconfont-archer">&#xe606;</span>Cookie</span>
    
        <span class="sidebar-tag-name" data-tags="Token"><span class="iconfont-archer">&#xe606;</span>Token</span>
    
        <span class="sidebar-tag-name" data-tags="Android"><span class="iconfont-archer">&#xe606;</span>Android</span>
    
        <span class="sidebar-tag-name" data-tags="Http"><span class="iconfont-archer">&#xe606;</span>Http</span>
    
        <span class="sidebar-tag-name" data-tags="Https"><span class="iconfont-archer">&#xe606;</span>Https</span>
    
        <span class="sidebar-tag-name" data-tags="OKHttp"><span class="iconfont-archer">&#xe606;</span>OKHttp</span>
    
        <span class="sidebar-tag-name" data-tags="Retrofit"><span class="iconfont-archer">&#xe606;</span>Retrofit</span>
    
        <span class="sidebar-tag-name" data-tags="Socket"><span class="iconfont-archer">&#xe606;</span>Socket</span>
    
        <span class="sidebar-tag-name" data-tags="TCP"><span class="iconfont-archer">&#xe606;</span>TCP</span>
    
        <span class="sidebar-tag-name" data-tags="UDP"><span class="iconfont-archer">&#xe606;</span>UDP</span>
    
        <span class="sidebar-tag-name" data-tags="IP"><span class="iconfont-archer">&#xe606;</span>IP</span>
    
    </div>
    <div class="iconfont-archer sidebar-tags-empty">&#xe678;</div>
    <div class="tag-load-fail" style="display: none; color: #ccc; font-size: 0.6rem;">
    缺失模块。<br>
    1、请确保node版本大于6.2<br>
    2、在博客根目录（注意不是archer根目录）执行以下命令：<br>
    <span style="color: #f75357; font-size: 1rem; line-height: 2rem;">npm i hexo-generator-json-content --save</span><br>
    3、在根目录_config.yml里添加配置：
    <pre style="color: #787878; font-size: 0.6rem;">
jsonContent:
  meta: false
  pages: false
  posts:
    title: true
    date: true
    path: true
    text: false
    raw: false
    content: false
    slug: false
    updated: false
    comments: false
    link: false
    permalink: false
    excerpt: false
    categories: true
    tags: true</pre>
    </div> 
    <div class="sidebar-tags-list"></div>
</div>
        <div class="sidebar-panel-categories">
    <div class="sidebar-categories-name">
    
        <span class="sidebar-category-name" data-categories="Camera"><span class="iconfont-archer">&#xe60a;</span>Camera</span>
    
        <span class="sidebar-category-name" data-categories="Android框架层"><span class="iconfont-archer">&#xe60a;</span>Android框架层</span>
    
        <span class="sidebar-category-name" data-categories="Android应用层"><span class="iconfont-archer">&#xe60a;</span>Android应用层</span>
    
    </div>
    <div class="iconfont-archer sidebar-categories-empty">&#xe678;</div>
    <div class="sidebar-categories-list"></div>
</div>
    </div>
</div> 
    <script>
    var siteMeta = {
        root: "/",
        author: "Yeungeek"
    }
</script>
    <!-- CDN failover -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>
    <script type="text/javascript">
        if (typeof window.$ === 'undefined')
        {
            console.warn('jquery load from jsdelivr failed, will load local script')
            document.write('<script src="/lib/jquery.min.js">\x3C/script>')
        }
    </script>
    <script src="/scripts/main.js"></script>
    <!-- algolia -->
    
    <!-- busuanzi  -->
    
    <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    
    <!-- CNZZ  -->
    
    </div>
    <!-- async load share.js -->
    
        <script src="/scripts/share.js" async></script>    
     
    </body>
</html>


